<template>
    <div id="fund-query">
        <div id="header">
            <el-form ref="searchParam" :model="searchParam">
                <el-form-item label="产品序号/名称" prop="productSerialNo" label-width="110px">
                    <el-select v-model="searchParam.productSerialNo" size="mini" filterable clearable style="width: 160px">
                        <el-option
                            v-for="item in fundIds"
                            :key="item.dictKey"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                            :value="item.dictKey"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="产品编码/名称" prop="productCode" label-width="110px">
                    <el-select v-model="searchParam.productCode" size="mini" filterable clearable style="width:160px">
                        <el-option v-for="item in fundInfos" :key="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName" :value="item.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="产品类型" prop="productType" label-width="100px">
                    <el-select v-model="searchParam.productType" size="mini" clearable style="width: 160px">
                        <el-option v-for="item in FundTypes" :key="item.dictKey" :label="item.dictKeyName" :value="item.dictKey"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="btn">
                <el-button type="primary" size="mini" @click="handleButton('search')">查询</el-button>
                <el-button size="mini" @click="handleButton('reset')">重置</el-button>
                <el-button type="primary" size="mini" @click="handleButton('refresh')">刷新</el-button>
            </div>
            <div style="position: absolute; right: 10px">
                <el-button type="primary" size="mini" @click="handleButton('doLayout')"> 布局设置</el-button>
            </div>
        </div>
        <div id="main-table-content">
            <vxe-table
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                highlight-current-row
                @cell-click="handleRow"
                @sort-change="changeTableSort"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
            >
                <vxe-column
                    v-for="item in showFieldList"
                    :field="item.id"
                    :title="item.content"
                    :key="item.content"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '105px'"
                    show-overflow="tooltip"
                    sortable
                >
                    <template slot-scope="scope">
                        <span v-if="formatParam.includes(item.id)">
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>
                        <span v-else-if="['nav', 'navYesterday', 'totalNav'].includes(item.id)">{{
                            numberFormat(scope.row[item.id], 4) || '--'
                        }}</span>
                        <span v-else>
                            {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>
        </div>

        <div id="tab-content">
            <el-tabs v-model="activeTab" type="card" @tab-click="handleClick">
                <el-tab-pane v-for="item in showPanes" :label="item.label" :name="item.name" :key="item.label"> </el-tab-pane>
            </el-tabs>
            <div style="float: right; margin-left: 20px"><el-button type="primary" @click="detailLayoutDialog = true">页面布局 </el-button></div>
        </div>

        <div style="margin-top: 10px">
            <keep-alive>
                <component
                    :is="activeComponent"
                    :transData="{ activeTab: activeTab, clickRow: clickRow, detailLayoutDialog: detailLayoutDialog }"
                    @layout-handle="layoutHandle"
                    v-if="isStart"
                ></component>
            </keep-alive>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_FUND_QUERY"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { checkPermission, numberFormat } from '@/utils/tools';
import { Component, Vue } from 'vue-property-decorator';
import AssetUnit from './fund-query/asset-unit.vue';
import BankCashTransaction from './fund-query/bank-cash-transaction.vue';
import BankHgTransaction from './fund-query/bank-hg-transaction.vue';
import BankOnWayHg from './fund-query/bank-on-way-hg.vue';
import Deal from './fund-query/deal.vue';
import DepositTransaction from './fund-query/deposit-transaction.vue';
import exchangeOnWayHg from './fund-query/exchange-on-way-Hg.vue';
import Instruction from './fund-query/instruction.vue';
import Position from './fund-query/position.vue';
import Entrust from './fund-query/entrust.vue';
import OuterConfirm from './fund-query/outer-confirm.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'FundQuery',
    components: {
        AssetUnit, // 单元资产信息
        BankOnWayHg, // 银行间在途回购查询
        exchangeOnWayHg, // 交易所在途回购查询
        Deal, // 成交查询
        BankCashTransaction, // 银行间现券成交查询
        BankHgTransaction, // 银行间回购成交查询
        Position, // 持仓查询
        Instruction, // 指令查询
        Entrust, // 委托查询
        OuterConfirm, // 场外开基成交查询
        RiskTableLayout,
        DepositTransaction, // 存款成交查询场外开基
        RiskPagination,
    },
})
export default class FundQuery extends Vue {
    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    detailLayoutDialog: boolean = false;

    numberFormat = numberFormat;

    Math = Math;

    layoutDialog: boolean = false;

    isStart: boolean = false; // 等产品表格数据到位后进行报表的渲染

    tableKey: number = -1;

    private sortProp: string = 'fundId'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    tabsKey: number = -1;

    clickRow: any = {}; // 点击行

    activeTab: string = 'AssetUnit';

    activeComponent: string = 'AssetUnit';

    formatParam = [
        'beginCash',
        'currentCash',
        'basicFrozenBalance',
        'fundTotalValue',
        'fundValue',
        'fundValueYesterday',
        'fundShare',
        'stockAsset',
        'bondAsset',
        'fundAsset',
        'hgAsset',
        'warrantAsset',
        'optionAsset',
        'otherAsset',
        'futuresDeposit',
    ];
    panes: any[] = [
        {
            label: '单元资产信息',
            name: 'AssetUnit',
            content: 'AssetUnit',
            authCode: 'B_0357',
        },
        {
            label: '委托查询',
            name: 'Entrust',
            content: 'Entrust',
            authCode: 'B_0358',
        },
        {
            label: '持仓查询',
            name: 'Position',
            content: 'Position',
            authCode: 'B_0359',
        },
        {
            label: '银行间在途回购查询',
            name: 'BankOnWayHg',
            content: 'BankOnWayHg',
            authCode: 'B_0360',
        },
        {
            label: '交易所在途回购查询',
            name: 'exchangeOnWayHg',
            content: 'exchangeOnWayHg',
            authCode: 'B_0361',
        },
        {
            label: '指令查询',
            name: 'Instruction',
            content: 'Instruction',
            authCode: 'B_0362',
        },
        {
            label: '成交查询',
            name: 'Deal',
            content: 'Deal',
            authCode: 'B_0363',
        },
        {
            label: '银行间现券成交查询',
            name: 'BankCashTransaction',
            content: 'BankCashTransaction',
            authCode: 'B_0364',
        },
        {
            label: '银行间回购成交查询',
            name: 'BankHgTransaction',
            content: 'BankHgTransaction',
            authCode: 'B_0365',
        },
        {
            label: '存款成交查询',
            name: 'DepositTransaction',
            content: 'DepositTransaction',
            authCode: 'B_0366',
        },
        {
            label: '场外开基成交查询',
            name: 'outer-confirm',
            content: 'OuterConfirm',
            authCode: 'B_0367',
        },
    ];

    tableData: any[] = []; // 表格数据

    summary: any = {}; // 汇总行

    loading: boolean = false; // 页面渲染

    showFieldList: any[] = []; // 显示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { content: '产品序号', id: 'fundId', align: 'left' },
        // { content: '产品编码', id: 'fundCode' },
    ];

    tableColumns = [
        { content: '产品序号', id: 'fundId', align: 'left' },
        // { content: '产品编码', id: 'fundCode' },
        { content: '产品名称', id: 'fundName', align: 'left' },
        { content: '产品类型', id: 'fundType', align: 'center' },
        { content: '期初资金余额', id: 'beginCash', minWidth: '130px' },
        { content: '当前资金余额', id: 'currentCash', minWidth: '130px' },
        { content: '保证金 ', id: 'basicFrozenBalance' },
        { content: '基金总资产', id: 'fundTotalValue', minWidth: '120px' },
        { content: '基金净资产', id: 'fundValue', minWidth: '120px' },
        { content: '基金昨日净资产', id: 'fundValueYesterday', minWidth: '150px' },
        { content: '基金总份额', id: 'fundShare', minWidth: '120px' },
        { content: '基金单位净值', id: 'nav', minWidth: '130px' },
        { content: '基金昨日单位净值', id: 'navYesterday', minWidth: '160px' },
        { content: '累计单位净值', id: 'totalNav', minWidth: '130px' },
        { content: '股票资产', id: 'stockAsset' },
        { content: '债券资产', id: 'bondAsset' },
        { content: '基金资产', id: 'fundAsset' },
        { content: '回购资产', id: 'hgAsset' },
        { content: '权证资产', id: 'warrantAsset' },
        { content: '期权资产', id: 'optionAsset' },
        { content: '其他资产', id: 'otherAsset' },
        { content: '期货保证金', id: 'futuresDeposit', minWidth: '120px' },
        { content: '币种', id: 'currencyNo', align: 'left', minWidth: '100px' },
        { content: '当前资金余额占净值(%)', id: 'currentCashPercent', minWidth: '200px' },
        { content: '股票资产占净值比(%)', id: 'stockAssetPercent', minWidth: '185px' },
        { content: '债券资产占净值比(%)', id: 'bondAssetPercent', minWidth: '185px' },
        { content: '基金资产占净值比(%)', id: 'fundAssetPercent', minWidth: '185px' },
        { content: '回购资产占净值比(%)', id: 'hgAssetPercent', minWidth: '185px' },
        { content: '权证资产占净值比(%)', id: 'warrantAssetPercent', minWidth: '185px' },
        { content: '期权资产占净值比(%)', id: 'optionAssetPercent', minWidth: '185px' },
        { content: '其他资产占净值比(%)', id: 'otherAssetPercent', minWidth: '185px' },
    ];
    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        fundCode: 'VC_FUND_CODE',
        fundName: 'VC_FUND_NAME',
        fundType: 'C_FUND_TYPE',
        beginCash: 'EN_BEGIN_CASH',
        currentCash: 'EN_CURRENT_CASH',
        basicFrozenBalance: 'EN_BASIC_FROZEN_BALANCE',
        fundTotalValue: 'EN_FUND_TOTAL_VALUE',
        fundValue: 'EN_FUND_VALUE',
        fundValueYesterday: 'EN_FUND_VALUE_YESTERDAY',
        fundShare: 'EN_FUND_SHARE',
        nav: 'EN_NAV',
        navYesterday: 'EN_NAV_YESTERDAY',
        totalNav: 'EN_TOTAL_NAV',
        stockAsset: 'EN_STOCK_ASSET',
        bondAsset: 'EN_BOND_ASSET',
        fundAsset: 'EN_FUND_ASSET',
        hgAsset: 'EN_HG_ASSET',
        warrantAsset: 'EN_WARRANT_ASSET',
        optionAsset: 'EN_OPTION_ASSET',
        otherAsset: 'EN_OTHER_ASSET',
        futuresDeposit: 'EN_FUTURES_DEPOSIT',
        currentCashPercent: 'TO_NUMBER(currentCashPercent)',
        stockAssetPercent: 'TO_NUMBER(stockAssetPercent)',
        bondAssetPercent: 'TO_NUMBER(bondAssetPercent)',
        fundAssetPercent: 'TO_NUMBER(fundAssetPercent)',
        hgAssetPercent: 'TO_NUMBER(hgAssetPercent)',
        warrantAssetPercent: 'TO_NUMBER(warrantAssetPercent)',
        optionAssetPercent: 'TO_NUMBER(optionAssetPercent)',
        otherAssetPercent: 'TO_NUMBER(otherAssetPercent)',
        currencyNo: 'VC_CURRENCY_NO',
    };

    // 查询字段
    searchParam: any = {
        // productCode: '',
        productSerialNo: '',
        productType: '',
        sort: 'L_FUND_ID ASC',
    };

    FundTypes: any[] = []; // 产品类型下拉值

    fundIds: any[] = []; // 产品序号下拉值

    // fundInfos: any[] = []; // 产品编码下拉值
    showPanes: any[] = [];

    async mounted() {
        let showPanes = [];
        this.panes.forEach(i => {
            if (checkPermission(i.authCode)) {
                showPanes.push(i);
            }
        });
        this.showPanes = showPanes;
        this.activeTab = this.showPanes[0].name;
        this.activeComponent = this.showPanes[0].content;
        // this.FundTypes = await SGU_CACHE('FundType', '/dict/list/code/Y_000002', []);

        await new Promise((resolve, reject) => {
            this.$axios
                .post('/reportDict/byCode', {
                    dictCode: '40001',
                })
                .then((res: any) => {
                    this.FundTypes = res;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        // await new Promise((resolve, reject) => {
        //     this.$axios
        //         .post('/reportDict/fund')
        //         .then((res: any) => {
        //             this.fundInfos = res;
        //             resolve(res);
        //         })
        //         .catch(err => {
        //             reject(err);
        //         });
        // });

        await new Promise((resolve, reject) => {
            this.$axios
                .post('/reportDict/fundId')
                .then((res: any) => {
                    this.fundIds = res;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        await this.queryLayout();

        await this.getTableData();

        this.isStart = true;
    }

    // 点击行
    handleClick(tab, event) {
        const temp = this.showPanes.find(item => item.name == this.activeTab);
        console.log(temp);
        this.activeComponent = temp.content;
    }

    // 页面布局返回值
    layoutHandle(value: boolean): void {
        this.detailLayoutDialog = value;
    }

    getTableData() {
        this.loading = true;
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/productSelect/list', {
                    paging: {
                        currentPage: this.page.currentPage,
                        pageSize: this.page.pageSize,
                    },
                    ...this.searchParam,
                })
                .then((res: any) => {
                    if (res.total) {
                        this.summary = res.list[res.list.length - 1];
                        this.tableData = res.list.slice(0, res.list.length - 1);
                        this.clickRow = this.tableData[0];
                        (this.$refs as any).table.setCurrentRow(this.tableData[0]);
                    } else {
                        this.tableData = [];
                    }
                    this.page.total = res.total;
                    this.loading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.loading = false;
                    reject(err);
                });
        });
    }

    // 按钮点击
    async handleButton(type: string) {
        if (type == 'reset') {
            (this.$refs['searchParam'] as any).resetFields();
        } else if (type == 'search') {
            await this.pageChange(1);
        } else if (type == 'refresh') {
            await this.pageChange(1);
            this.activeTab = 'AssetUnit';
            this.activeComponent = 'AssetUnit';
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        }
    }

    async sizeChange(pageSize: number) {
        await this.getTableData();
    }

    async pageChange(curPage: number) {
        this.page.currentPage = curPage;
        await this.getTableData();
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let obj = this.tableData[0];
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
            console.log([arr]);
        }
        return [arr];
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.searchParam.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    // 点击行
    handleRow({ row }) {
        this.clickRow = row;
        this.detailLayoutDialog = false;
        // this.tabsKey++;
    }

    pageRet() {
        this.getTableData();
    }
    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        this.loading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_FUND_QUERY')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        let keys = ['fundId'];
        //  'fundCode'
        if (!resList) {
            // 新用户初始化
            this.selectedFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.selectedFieldList = [];
            } else {
                this.selectedFieldList = JSON.parse(resList);
            }
        }
        this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);

        this.tableKey++;
        this.loading = false;
    }

    // beforeUpdate() {
    //     this.$nextTick(() => {
    //         // 在数据加载完，重新渲染表格
    //         (this.$refs['table'] as any).doLayout();
    //     });
    // }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';

#fund-query {
    width: 100%;
    min-width: 1200px;
    padding: 20px 10px 0 10px;
    #header {
        display: flex;
        position: relative;
        align-items: center;
        .btn {
            margin-left: 20px;
        }

        /deep/.el-form {
            display: flex;
            .el-form-item {
                // display: inline-block;
                margin-bottom: 0px;
                .el-form-item__label {
                    color: black;
                    padding-right: 2px;
                }
            }
        }
    }
    #main-table-content {
        margin-top: 10px;
    }
    #tab-content {
        display: flex;
        justify-content: space-between;
    }
}
/deep/ .el-pagination {
    padding: 6px 6px 6px 0 !important;
}
/deep/ .el-tabs > .el-tabs__header .el-tabs__item {
    border: 1px solid #e4e7ed;
    // border-bottom: none;
    padding: 0 14px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    &:nth-child(2) {
        padding-left: 14px;
    }
    &:last-child {
        padding-right: 14px;
    }
}
/deep/ .el-tabs .el-tabs__nav {
    border: none;
    .is-active {
        border-color: #409eff;
        border-bottom: 2px solid #409eff;
    }
}

/deep/ .el-tabs--card > .el-tabs__header {
    border-bottom: none;
}

/deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(50vh - 160px);
    }
}
</style>
